from django.db.models import Q
from django.template import *
from l2ldjango.apps.mailmanagement.models import *
from django.middleware import *
from django.contrib.auth.models import User
from django.core.files.base import ContentFile
from django.shortcuts import *
from django.template.loader import get_template
from l2ldjango.apps.usermanagement.models import *
from django.core.mail import send_mail
from django.core.files.uploadedfile import SimpleUploadedFile
from django.middleware import *
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.mail import send_mail
from l2ldjango.apps.mailmanagement.forms import *
from django.contrib.auth.decorators import login_required
from l2ldjango.apps.personal_messages.models import Message
from l2ldjango.apps.personal_messages.forms import *
import simplejson as json
from django.contrib import messages
    
@login_required
def reply_view(request,the_id=None):
    
    try:
        in_response_to = Message.objects.get(to_user=request.user,id=the_id)
    except:
        raise Http404
    
    if request.POST:
        form = ReplyForm(request.POST)
        if form.is_valid():
            print 'Sending response.'
            
            message = Message()
            message.in_response_to = in_response_to
            message.to_user = in_response_to.from_user
            message.from_user = request.user
            message.subject = 'RE: %s' % in_response_to.subject
            message.message = form.cleaned_data['reply']
            message.save()
            
            
        else:
            print form.errors
            return HttpResponseRedirect('/l2l/messages/%s' % in_response_to.id)
            
        
    
    return HttpResponseRedirect('/l2l/messages/')

@login_required
def delete_view(request,the_id=None):
    
    try:
        Message.objects.get(to_user=request.user,id=the_id).delete()
    except:
        raise Http404
    
    return HttpResponseRedirect('/l2l/messages/')

@login_required
def detail_view(request,the_id=None):
    
    try:
        message = Message.objects.get(to_user=request.user,id=the_id)
    except:
        raise Http404
    
    form = ReplyForm()
    
    variables = RequestContext(request,{'message':message,
                                        'form':form})
    return render_to_response('personal_messages/message_detail.html',variables)
    
@login_required
def lookup_view(request):
    
    try:
        input = request.GET['term']
    except:
        input = None
    
    return_array = []
    
    if input:
        
        q = input.lower()
        
        profiles = userprofile.objects.filter(full_name__icontains=q)[:5]
        
        for profile in profiles:
            formatted_name = '%s %s' % (profile.first_name.title(),profile.last_name.title())
            if profile.city and profile.state:
                formatted_name = '%s (%s, %s)' % (formatted_name,profile.city,profile.state)
            return_array.append({"id":profile.id,"label":formatted_name,"value":'%s %s' % (profile.first_name.title(),profile.last_name.title())})
            
    else:
        return_array.append({"id":None,"label":"No user found for %s ..." % input,"value":q})
    
    return HttpResponse(json.dumps(return_array), mimetype="application/json")       

@login_required
def index_view(request):
    
    personal_messages = Message.objects.filter(to_user=request.user)
    
    variables = RequestContext(request,{'personal_messages':personal_messages})
    
    return render_to_response('personal_messages/messages.html',variables)

@login_required
def compose_view(request):
    form = ComposeForm(initial={'from_user':request.user})
    if request.POST:
        form = ComposeForm(request.POST)
        if form.is_valid():
            
            userprofile_to_send = userprofile.objects.get(id=form.cleaned_data['to_person_id'])
            
            if userprofile_to_send.user:
                
                new_message = Message()
                new_message.from_user = request.user
                new_message.to_user = userprofile_to_send.user
                new_message.subject = form.cleaned_data['subject']
                new_message.message = form.cleaned_data['message']
                new_message.save()
                
                return HttpResponseRedirect('/l2l/messages/')
            
            else:
                messages.add_message(request, messages.INFO, 'This attorney has not activated his/her account. Please try again later.')
                return HttpResponseRedirect('/l2l/users/view-profile/%s/'  % userprofile_to_send.id)
                
    variables = RequestContext(request,{'form':form})
    return render_to_response('personal_messages/compose_message.html',variables)